#!/bin/bash

R="\\033[1;31m"
V="\\033[1;32m"
J="\\033[1;33m"
N="\\033[0;39m"

if [ $USER != "root" ]; then
	echo -n "$R"
	echo -n "Doit être lancé en tant que root."
	echo "$N"
	exit 1
fi

CUR_DIR=`pwd`

LOG_FILE=$CUR_DIR/mantisbt-install-`date +"%Y%m%d%H%M%S"`.log

touch $LOG_FILE

# Installation de mysql diff
echo -n "Installation de Mantis Bug Tracker : "

# Création du dossier principal si besoin.
if [ ! -d "/opt/php-factory" ]; then
        mkdir /opt/php-factory
fi

cd /opt/php-factory

tar -xzf $CUR_DIR/repository/mantisbt-1.2.0.tar.gz &>> $LOG_FILE

if [ "$?" = 0 ]; then
	echo -e "$V OK $N"
else
	echo -e "$R KO $N"
	exit 1
fi 

# Création du dossier de config si besoin.
if [ ! -d "/etc/php-factory" ]; then
        mkdir /etc/php-factory
fi

if [ ! -d "/etc/php-factory/mantisbt-1.2.0" ]; then
        mkdir /etc/php-factory/mantisbt-1.2.0
fi

cp $CUR_DIR/conf/mantisbt-vhost.conf-dist /etc/php-factory/mantisbt-1.2.0/apache2.conf

ln -s /etc/php-factory/mantisbt-1.2.0/apache2.conf /etc/apache2/sites-enabled/mantisbt.conf

mv /opt/php-factory/mantisbt-1.2.0/config_inc.php.sample /etc/php-factory/mantisbt-1.2.0/config.php

ln -s /etc/php-factory/mantisbt-1.2.0/config.php /opt/php-factory/mantisbt-1.2.0/config_inc.php

# todo: déplacer ces variables dans un fichier de conf (ou demandée au début et exportées, cleanées en cas d'échec)
SQL_ADM_USR="root"
SQL_ADM_PWD="7923"

SQL_USR="mantisbt"
SQL_PWD="mantisbt"
SQL_DBN="mantisbt"

# Création de l'utilisateur et de la table.
mysql --host=localhost --user=$SQL_ADM_USR --password=$SQL_ADM_PWD --execute="CREATE USER '$SQL_USR'@'localhost' IDENTIFIED BY '$SQL_PWD'; GRANT USAGE ON * . * TO '$SQL_USR'@'localhost' IDENTIFIED BY '$SQL_PWD' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ; CREATE DATABASE IF NOT EXISTS \`$SQL_DBN\` ; GRANT ALL PRIVILEGES ON \`$SQL_DBN\` . * TO '$SQL_USR'@'localhost';"

# Création du schéma de base et insertion des données d'origine.
mysql --host=localhost --user=$SQL_ADM_USR --password=$SQL_ADM_PWD --execute="source $CUR_DIR/conf/mantisbt.sql"

# Configuration
# todo: Personnaliser
sed -i "s/\$g_hostname      = 'localhost';/\$g_hostname      = 'localhost';/" /etc/php-factory/mantisbt-1.2.0/config.php
sed -i "s/\$g_db_username   = 'mantisdbuser';/\$g_db_username   = 'mantisbt';/" /etc/php-factory/mantisbt-1.2.0/config.php
sed -i "s/\$g_db_password   = '';/\$g_db_password   = 'mantisbt';/" /etc/php-factory/mantisbt-1.2.0/config.php
sed -i "s/\$g_database_name = 'bugtracker';/\$g_database_name = 'mantisbt';/" /etc/php-factory/mantisbt-1.2.0/config.php
sed -i "s/\$g_db_type       = 'mysql';/\$g_db_type       = 'mysql';/" /etc/php-factory/mantisbt-1.2.0/config.php

rm -rf /opt/php-factory/mantisbt-1.2.0/admin

sudo chown --recursive www-data:www-data /opt/php-factory/mantisbt-1.2.0

# todo: ajout du produit aux produits du backoffice

service apache2 reload

